<?php
namespace Kcdns\Admin\Widget;
use \Think\Controller;

class DataformWidget extends Controller
{

    public function run ($cfg, $_data, $url = null, $list = null)
    {
        foreach ($_data as $k => $v)
        {
            $data[$cfg->escape($k)] = $v;
        }
        
        $this->_toModel($cfg, $data);
        $this->data = $data;
        $this->url = $url ?  : $_SERVER['REQUEST_URI'];
        $this->list_extra = $list; // 额外列表，例如 model 的字段列表
        $this->showFieldsConditons = $this->_showFieldsConditions($data);
        $this->ctl = $this;
        $this->cfgFields = $cfg->formField;
        
        $this->display("Widget/dataform");
    }
    
    // 表单拓展插件
    public function inputExtend ($field)
    {
        $this->assign('field', $field);
        $this->display($field['type']);
    }
    
    // 表单定义兼容处理
    protected function _toModel ($cfg, $data)
    {
        $group = [];
        $index = 1;
        $idPrefix = uniqid();
        $fieldGroupString = '';
        $fieldGroupSet = [];
        $i = 0;
        
        if (is_array($cfg->formField))
        {
            foreach ($cfg->formField as &$v)
            {
                // 字段分组
                if (! isset($group[$v['group']]))
                {
                    $group[$v['group']] = $index ++;
                }
                
                $v['name'] = $cfg->escape($v['name']);
                $v['value'] = $data[$v['name']];
                $v['id'] = $idPrefix . $i ++;
                $fieldGroupSet[$group[$v['group']]][] = $v;
            }
        }
        
        $this->groups = array_flip($group);
        $this->fields = $fieldGroupSet;
    }

    protected function _showFieldsConditions ($data)
    {
        $formType = '';
        
        // 通过控制器名称检测
        strpos(ACTION_NAME, 'add') !== false and $formType = 'add';
        strpos(ACTION_NAME, 'edit') !== false and $formType = 'edit';
        
        // 通过是否有数据判断, 默认显示新增表单
        $formType or $formType = $data['id'] ? 'edit' : 'add';
        
        $showCondition = array(
                'add' => array(
                        '',
                        '1',
                        '2'
                ),
                'edit' => array(
                        '',
                        '1',
                        '3'
                )
        );
        
        return $showCondition[$formType];
    }
}